import json
import matplotlib.pyplot as plt

# 重新计算 final_score 的公式
def calculate_final_score(pattern_match_score, key_coverage_score, redundancy_score):
    return pattern_match_score * 0.2 + key_coverage_score * 0.8 - redundancy_score * 0.05

# 读取原始JSON文件
def load_evaluation_results(file_path):
    with open(file_path, 'r') as f:
        data = json.load(f)
    return data

# 重新计算并覆盖 final_score
def update_final_scores(results):
    for result in results:
        pattern_match_score = result['pattern_match_score']
        key_coverage_score = result['key_coverage_score']
        redundancy_score = result['redundancy_score']
        final_score = calculate_final_score(pattern_match_score, key_coverage_score, redundancy_score)
        result['final_score'] = final_score
    return results

# 保存更新后的结果到新的JSON文件
def save_updated_evaluation_results(results, output_path):
    with open(output_path, 'w') as f:
        json.dump(results, f, indent=4)


# 计算平均得分并生成分布图
def calculate_average_score_and_plot(results):
    final_scores = [result['final_score'] for result in results]
    average_score = sum(final_scores) / len(final_scores)

    # 生成分布图
    plt.hist(final_scores, bins=10, edgecolor='black')
    plt.title('Final Score Distribution')
    plt.xlabel('Final Score')
    plt.ylabel('Frequency')
    plt.show()

    return average_score

if __name__ == "__main__":
    input_file_path = 'data/iu_xray/iu_xray/evaluation_results_new.json'
    output_file_path = 'data/iu_xray/iu_xray/updated_evaluation_results.json'

    evaluation_results = load_evaluation_results(input_file_path)
    updated_results = update_final_scores(evaluation_results)
    save_updated_evaluation_results(updated_results, output_file_path)
    print(f"Updated evaluation results saved to {output_file_path}")

    average_score = calculate_average_score_and_plot(evaluation_results)
    print(f"Average Final Score: {average_score}")

    # result = updated_results
   
    # 这里还是出了一些bugs,但是错误还是存在，这里修改为平均分，并做好记录
    # 后续参数计算会进行下一步修改
     # 计算下属三个指标分数的平均值
    pattern_match_scores = [result['pattern_match_score'] for result in evaluation_results]
    key_coverage_scores = [result['key_coverage_score'] for result in evaluation_results]
    redundancy_scores = [result['redundancy_score'] for result in evaluation_results]

    average_pattern_match_score = sum(pattern_match_scores) / len(pattern_match_scores)
    average_key_coverage_score = sum(key_coverage_scores) / len(key_coverage_scores)
    average_redundancy_score = sum(redundancy_scores) / len(redundancy_scores)

    print(f"Average Pattern Match Score: {average_pattern_match_score}")
    print(f"Average Key Coverage Score: {average_key_coverage_score}")
    print(f"Average Redundancy Score: {average_redundancy_score}")
